package com.samuel.blog.controller.admin;

import com.github.pagehelper.PageInfo;
import com.samuel.blog.bean.PageBean;
import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.controller.BaseController;
import com.samuel.blog.entity.AuthorEntity;
import com.samuel.blog.entity.RoleEntity;
import com.samuel.blog.service.AuthorService;
import com.samuel.blog.service.RoleService;
import com.samuel.blog.utils.Md5Utils;
import com.samuel.blog.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kaiji
 */
@Controller
@RequestMapping("admin")
public class AuthorController extends BaseController {

	private static final long serialVersionUID = 3391206046089127437L;
	private static final Logger logger = Logger.getLogger(AuthorController.class);
	private static final String PRE = "author/";
	private static final String PRE_PAGER = "admin/author_";
	
	@Resource(name = "authorService")
	private AuthorService authorService;
	@Resource(name = "roleService")
	private RoleService roleService;

	/**
	 * 查询个人信息
	 * @return
	 */
	@RequestMapping(value = PRE+"profile"+SUFFIX, method = RequestMethod.GET)
	public String profile() {
		return PRE_PAGER+"profile";
	}
	
	/**
	 * 保存个人信息
	 * @param request
	 * @param response
	 * @param authorEntity 作者对象
	 * @return
	 */
	@RequestMapping(value = PRE+"profile"+SUFFIX, method = RequestMethod.POST)
	public String saveProfile(HttpServletRequest request, HttpServletResponse response, AuthorEntity authorEntity) {
		return PRE_PAGER+"profile";
	}
	
	@RequestMapping(value = PRE+"list"+SUFFIX, method = RequestMethod.GET)
	public String list(HttpServletRequest request){
		this.configCss(request, "author", "author_info");
		return PRE_PAGER+"list";
	}
	
	/**
	 * 查询全部信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = PRE+"list"+SUFFIX, method = RequestMethod.POST)
	public String tolist(HttpServletRequest request, HttpServletResponse response, PageBean pageBean, AuthorEntity author) {
		this.configCss(request, "author", "author_info");
		
		// 传入动态条件
		Map<String, Object> dynamicParam = new HashMap<>();
		if (!StringUtils.empty(author.getPhone())) {
			dynamicParam.put("phone", author.getPhone());
		}
		if (!StringUtils.empty(author.getUserName())) {
			dynamicParam.put("userName", author.getUserName());
		}
		// 获取当前数据的在的当前页数
		PageInfo<AuthorEntity> pageInfo = authorService.selectPage(pageBean, dynamicParam);
		
		this.returnTableData(pageBean, pageInfo, response);
		return null;
	}
	

	/**
	 * get方式 进入登录页面
	 * @return
	 */
	@RequestMapping(value = PRE+"login"+SUFFIX, method = RequestMethod.GET)
	public String toLogin() {
		return PRE_PAGER+"login";
	}
	
	@RequestMapping(value = PRE+"login"+SUFFIX, method = RequestMethod.POST)
	@ResponseBody
	public String login(HttpServletRequest request, HttpServletResponse response, AuthorEntity author) {
		String message = "登录成功!";
		if (null == author) {
			message = "用户和密码不能为空!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (StringUtils.empty(author.getPhone())) {
			message = "请输入手机号码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (StringUtils.empty(author.getPassword())) {
			message = "请输入密码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;

		}
		AuthorEntity authorEntity = authorService.getByPhone(author.getPhone());
		if (null == authorEntity) {
			message = "账户不正确!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (authorEntity.getDeleteStatus() == CommonConstant.STOP_USE) {
			message = "该账户已删除";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		String password = author.getPassword();
		password = Md5Utils.getMD5Str(password);
		if (!password.equals(authorEntity.getPassword())) {
			message = "密码不正确!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		// 更新作者的登录信息
		AuthorEntity ae = new AuthorEntity();
		ae.setAuthorId(authorEntity.getAuthorId());
		ae.setLoginIp(StringUtils.getRemoteAddr(request));
		ae.setModiftyDate(new Date());
		authorService.saveRedis(ae);
		// 存储对象
		this.destroySession(request, CommonConstant.USER_LOGIN_SESSION_KEY);
		this.saveByKey(request, CommonConstant.USER_LOGIN_SESSION_KEY, authorEntity);
		logger.info(message);
		ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
		return null;
	}
	
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"logout"+SUFFIX)
	public String logout(HttpServletRequest request) {
		logger.info("开始退出~~!");
		this.destroySession(request, CommonConstant.USER_LOGIN_SESSION_KEY);
		logger.info("退出成功~~!");
		return "redirect:admin/author/login.html";
	}
	
	/**
	 * 修改个人信息 博客名, 真实姓名, 登录账号, 等级
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"update"+SUFFIX, method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpServletRequest request, HttpServletResponse response, AuthorEntity author) {
		logger.info("<-----------开始验证---------------->");
		String message = "修改成功!";
		if (null == author) {
			message = "必填项不能为空!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getUserName())) {
			message = "请输入博客名!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getRealName())) {
			message = "请输入真实名称!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getPhone())) {
			message = "请输入电话号码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (author.getPhone().length() != 11) {
			message = "请输入正确格式的电话号码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (StringUtils.empty(author.getAuthorId())) {
			message = "请刷新重试!";
			logger.error("id 是必须的, id不存在, 不能执行修改操作");
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		AuthorEntity ae = authorService.selectById(author.getAuthorId());
		if (null == ae) {
			message = "请刷新重试!";
			logger.error("对象不存在, 不能执行修改操作!");
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		// 判断真实姓名是否存在, 电话号码是否重复, 昵称是否重复
		ae = authorService.getByPhone(author.getPhone());
		if (ae != null && !ae.getAuthorId().equals(author.getAuthorId())) { // 重复 
			message = "登录号码重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		ae = authorService.getByRealName(author.getRealName());
		if (ae != null && !ae.getAuthorId().equals(author.getAuthorId())) { // 重复 
			message = "真实姓名重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		ae = authorService.getByUserName(author.getUserName());
		if (ae != null && !ae.getAuthorId().equals(author.getAuthorId())) { // 重复 
			message = "博客名重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		logger.info("<-----------验证通过---------------->");
		
		logger.info("<-----------执行修改操作---------------->");
		int num = authorService.updateById(author);
		if (num > 0) {
			logger.info(((AuthorEntity)getSessionByKey(request, null)).getRealName() + "<-----------: 执行修改操作---------------->");
			ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
		} else {
			logger.error(((AuthorEntity)getSessionByKey(request, null)).getRealName() + "<-----: 执行更新失败-------->");
			message = "更新失败!";
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
		}
		return null;
	}
	
	/**
	 * 删除数据  所有的删除都逻辑删除
	 * @param request
	 * @param response
	 * @param ids  //批量删除作者信息  
	 * @return
	 */
	@RequestMapping(value = PRE+"delete"+SUFFIX, method = RequestMethod.POST)
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, @RequestParam("ids[]") String[] ids) {
		String message = "删除失败!";
		if (null == ids || ids.length <= 0) { // 重复 
			message = "请至少选择一项!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		boolean falg = authorService.deleteBatchByIds(ids);
		if (falg) {
			logger.info(((AuthorEntity)getSessionByKey(request, null)).getRealName() + "<-----------: 执行逻辑删除成功---------------->");
			ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
		} else {
			logger.error(((AuthorEntity)getSessionByKey(request, null)).getRealName() + "<-----: 执行逻辑删除失败-------->");
			message = "更新失败!";
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
		}
		return null;
	}
	
	/**
	 * 保存新作者信息
	 * @return
	 */
	@RequestMapping(value = PRE+"save"+SUFFIX, method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request, HttpServletResponse response, AuthorEntity author) {
		logger.info("<-----------开始验证---------------->");
		String message = "修改成功!";
		if (null == author) {
			message = "必填项不能为空!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getUserName())) {
			message = "请输入博客名!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getRealName())) {
			message = "请输入真实名称!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getPhone())) {
			message = "请输入电话号码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (author.getPhone().length() != 11) {
			message = "请输入正确格式的电话号码!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		if (!StringUtils.empty(author.getAuthorId())) {
			message = "请刷新重试!";
			logger.error("id不能存在, 不能执行修改操作");
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		// 判断真实姓名是否存在, 电话号码是否重复, 昵称是否重复
		AuthorEntity ae = authorService.getByPhone(author.getPhone());
		if (ae != null) { // 重复 
			message = "登录号码重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		ae = authorService.getByRealName(author.getRealName());
		if (ae != null) { // 重复 
			message = "真实姓名重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		
		ae = authorService.getByUserName(author.getUserName());
		if (ae != null) { // 重复 
			message = "博客名重复!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		}
		if (StringUtils.empty(author.getPassword())) {
			message = "密码不能为空!";
			logger.error(message);
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
			return null;
		} else {
			String md5Str = Md5Utils.getMD5Str(author.getPassword());
			author.setPassword(md5Str);
			author.setCreateDate(new Date());
			author.setDeleteStatus(0);
			author.setResource(0);
			author.setLoginIp(StringUtils.getRemoteAddr(request));
		}
			
		logger.info("<-----------验证通过---------------->");
		int num = authorService.insert(author);
		if (num > 0) {
			logger.info("<-----------author 保存成功---------------->");
			ajax(response, CommonConstant.NoticeCode.SUCCESS_ONE, message);
		} else {
			logger.error("<-----------author 保存失败---------------->");
			ajax(response, CommonConstant.NoticeCode.ERROR_ZERO, message);
		}
		return null;
	}
	
	/**
	 * 进入设置角色页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"role"+SUFFIX, method = RequestMethod.GET)
	public String roRole(HttpServletRequest request, String authorId) {
		this.configCss(request, "author", "author_info");
		if (StringUtils.empty(authorId)) {
			logger.error("authorId是必须的！");
			request.setAttribute("message", "请刷新重试！");
			return MESSAGE_PAGE;
		}
		
		AuthorEntity authorEntity = authorService.selectById(authorId);
		if (null == authorEntity) {
			logger.error("对象是必须的！");
			request.setAttribute("message", "对象不存在，请刷新重试！");
			return MESSAGE_PAGE;
		}
		// 获取我自己的角色
		RoleEntity roleEntity = roleService.selectByAuthorId(authorId);
		// 查询全部的角色
		List<RoleEntity> roleList = roleService.selectAll();
		request.setAttribute("roleEntity", roleEntity);
		request.setAttribute("roleList", roleList);
		request.setAttribute("authorId", authorId);
		return PRE_PAGER+"role";
	}
	
	/**
	 * 进入设置角色页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = PRE+"role"+SUFFIX, method = RequestMethod.POST)
	public String role(HttpServletRequest request, String authorId, String roleId) {
		try {
			if (StringUtils.empty(authorId)) {
				String message = "authorId 是必须的！";
				logger.error(message);
				request.setAttribute("message", "对象不存在，请刷新重试！");
				return MESSAGE_PAGE;
			}
			int num = authorService.saveAuthorRole(authorId, roleId);
			if (num > 0) {
				return REDIRECT+"/admin/author/list.html";
			} else {
				request.setAttribute("message", "保存角色失败！");
				return MESSAGE_PAGE;
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", e.getMessage());
			return MESSAGE_PAGE;
		}
	}
}
